package com.java47.controller;

import com.github.pagehelper.Page;
import com.java47.pojo.Posting;
import com.java47.pojo.Reply;
import com.java47.service.PostingService;
import com.java47.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PostingAction {

    @Autowired
    private PostingService ps;
    private static String ppid="";
    private static Page<Object> page;

    @RequestMapping("showAll")
    private String showAll(String index, String str, HttpSession session){
        if(index==null){
            index="1";
        }
        page = ps.showPage(Integer.parseInt(index),3,str);
        session.setAttribute("select",str);
        session.setAttribute("page",page);
        return "index";
    }

    @RequestMapping("show")
    @ResponseBody
    public List<Posting> show(){
        List<Posting> list = (List) page;
        for(int i =0;i<list.size();i++){
            list.get(i).setPtime(Util.getJson(list.get(i).getCreatedate(),"yyyy-MM-dd"));
        }
        return list;
    }

    @RequestMapping("tohuifu")
    private String tohuifu(String pid){
        if(pid!=null) {
            ppid=pid;
        }
        return "huifu";
    }

    @RequestMapping("huifu")
    @ResponseBody
    private List<Reply> huifu(){
        String pid = ppid;
        List<Reply> rlist = ps.showRlist(ppid);
        for(int i =0;i<rlist.size();i++){
            rlist.get(i).setRtime(Util.getJson(rlist.get(i).getCreatedate(),"yyyy-MM-dd"));
        }
        return rlist;
    }

    @RequestMapping("add")
    private String add(String author, String content, Model model){
        Map<String,Object> map = new HashMap<>();
        map.put("pid",ppid);
        map.put("content",content);
        map.put("author",author);
        int num = 0;
        if(!content.equals("")){
            num = ps.add(map);
        }
        String str = "";
        if(num>0){
            str="回复成功！";
        }else{
            str="回复失败！";
        }
        model.addAttribute("str",str);
        return "forward:tohuifu";
    }


}
